﻿
using ETModel;

namespace ETHotfix {
    /// <summary>
    /// 管理Gate服务器上客户端的Session,对应的玩家的组件,本组件销毁就认为session断开了<para/>
    /// Gate登录成功后(调用"gateSession.GatePlayerLoginSuccess(...)")后会自动附加给session<para/>
    /// 或者Gate断线重连(调用"gateSession.GatePlayerReconnect(...)")后会自动附加给session<para/>
    /// </summary>
    public class GateClientSessionPlayerComponent : Component {
        private GatePlayer _player;
        private long _playerInsId;

        /// <summary>
        /// 会话对应的玩家对象
        /// </summary>
        public GatePlayer Player {
            set {
                _player = value;
                if (_player != null) {
                    _playerInsId = _player.InstanceId;
                } else {
                    _playerInsId = 0;
                }
            }
            get {
                if (_player?.InstanceId != _playerInsId) {
                    _player = null;
                }
                return _player;
            }
        }

        /// <summary>
        /// 销毁不会连带销毁Player,只是把本组件的引用删除
        /// </summary>
        public override void Dispose() {
            if (IsDisposed) return;
            base.Dispose();
            if (Player != null) {
                Player = null;
            }
        }
    }
    /// <summary>
    /// 
    /// </summary>
    [ObjectSystem]
    public class GateClientSessionPlayerComponentDestroySystem : DestroySystem<GateClientSessionPlayerComponent> {
        public override void Destroy(GateClientSessionPlayerComponent self) {
            if (self.Player != null) {
                //将玩家关联的session置空
                self.Player.Parent = null;
                //丢到断线重连等待
                Game.Scene.GetComponent<GatePlayerWaitReconnectComponent>().GatePlayerDisconnect(self.Player);
            }
        }
    }
}